package com.xuanrui.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.core.AdapayCore;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.core.util.AdapaySign;
import com.huifu.adapay.model.Payment;
import com.xuanrui.commons.*;
import com.xuanrui.commons.enums.ChargeRecordsStatusEnum;
import com.xuanrui.commons.enums.PayTypeEnum;
import com.xuanrui.config.TokenVO;
import com.xuanrui.config.adapay.AdapayItemConfig;
import com.xuanrui.config.adapay.AdapayUtil;
import com.xuanrui.dto.PayDTO;
import com.xuanrui.modelExt.ChargeRecordsExt;
import com.xuanrui.pubInter.SkJsonResult;
import com.xuanrui.service.IChargeRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author afeng
 * @version 1.0
 * @date 2023/11/15 下午5:35
 */
@RequestMapping("/adapay/")
@RestController
public class AdapayController extends ApiRestController {
    @Value("${game.sign}")
    private String urlSign;
    @Value("${game.startUrl}")
    private String startUrl;
    @Value("${game.okUrl}")
    private String okUrl;
    @Value("${game.notifyUrl}")
    private String notifyUrl;


    @Autowired
    private IChargeRecordsService chargeRecordsService;
    @Autowired
    private AdapayUtil adapayUtil;

    @PostMapping("pay")
    public SkJsonResult<Map<String, String>> pay(@RequestBody PayDTO payDTO, HttpServletRequest request, HttpSession session) throws Exception {
//                TokenVO token= (TokenVO) session.getAttribute("wechatAuthorization");
//        if(StringUtil.isObjEmpty(token)){
//            return SkJsonResult.ok();
//        }
        System.out.println("=======execute payment begin=======");
        String openId = payDTO.getOpenId();
        String wxAppId = payDTO.getAppId();
        System.out.println("接受的openId:"+openId);
//        System.out.println("openId:"+token.getOpenId());
//        System.out.println("wxAppId:"+token.getWxAppId());
//
//        String openId = "oghtz6kg6C4KYR4NvQI84x-f2OOQ";
//        String wxAppId = "wxa16b486ee8fc0c8e";

//        TokenVO token = getToken(request);
//        String openId = token.getOpenId();
//        String wxAppId = token.getWxAppId();


        AdapayItemConfig adapayItemConfig = adapayUtil.getOneAdapayConfigByAppId(wxAppId);


        String apiKey = adapayItemConfig.getApiKey();
        String payKey = adapayItemConfig.getPayKey();
        String appId = adapayItemConfig.getAppId();



        //创建支付对象的参数，全部参数请参考 https://docs.adapay.tech/api/index.html
        Map<String, Object> paymentParams = new HashMap<>(10);

//        paymentParams.put("adapay_connection_request_timeout", 5000);
//        paymentParams.put("adapay_connect_timeout", 5000);
//        paymentParams.put("adapay_socket_timeout", 5000);
//        paymentParams.put("adapay_region", "beijing");


        String orderNo = payKey + StringUtil.createOrderNo(6) + System.currentTimeMillis();
        float money = payDTO.getPayMoney();
        String payMoney = String.format("%.2f", NumberUtil.divideBigDecimal(new BigDecimal(money), new BigDecimal(100)));

        paymentParams.put("app_id", appId);
        paymentParams.put("order_no", orderNo);
        paymentParams.put("pay_channel", "wx_pub");
        paymentParams.put("pay_amt", payMoney);
        paymentParams.put("goods_title", "充值");
        paymentParams.put("goods_desc", "充值金额");
        paymentParams.put("description", payDTO.getPlayerId());
        paymentParams.put("div_members", "");

        Map<String, Object> deviceInfo = new HashMap<>(2);
//设备ip
        deviceInfo.put("device_ip", HttpTookit.getIpAddr(request));
        paymentParams.put("device_info", deviceInfo);
//其他相关信息
        Map<String, Object> expendParams = new HashMap<>(2);
        expendParams.put("open_id", openId);
        expendParams.put("is_raw", "1");
        paymentParams.put("expend", expendParams);
        paymentParams.put("notify_url", notifyUrl);


        ChargeRecordsExt chargeRecords = new ChargeRecordsExt();
        chargeRecords.setCreateTime(new Date().getTime());
        chargeRecords.setUpdateTime(new Date().getTime());
        chargeRecords.setId(IdGen.uuid());
        chargeRecords.setTotalFee(money);
        chargeRecords.setPayPlayerId(payDTO.getPlayerId());
        chargeRecords.setPayType(PayTypeEnum.WECHAT_PUBLIC.getType());
        chargeRecords.setOrderNo(orderNo);
        chargeRecords.setStatus(ChargeRecordsStatusEnum.NEW.getType());
        chargeRecords.setWxAppId(wxAppId);
        chargeRecordsService.insert(chargeRecords);

        //调用sdk方法，创建支付，得到支付对象
        Map<String, Object> payment = new HashMap<>();
        try {
            System.out.println("支付交易，请求参数：" + JSON.toJSONString(paymentParams));
            payment = Payment.create(paymentParams, apiKey);
            System.out.println("支付交易，请求j：" + JSON.toJSONString(payment));
        } catch (BaseAdaPayException e) {
            e.printStackTrace();
        }

        if (StringUtil.equal((String) payment.get("status"), "succeeded")) {

            String postParamsStr = "payment=0&out_trade_no=" + orderNo + "&total_fee=" + money + "&playerid=" + payDTO.getPlayerId() + "&toid=" + payDTO.getToId() + "&sign=" + urlSign;
            System.out.println("start请求结果参数" + postParamsStr);

            String res = HttpTookit.doGet(startUrl, postParamsStr);

            if (StringUtil.equal(res, "999999")) {
                chargeRecords.setStartUrl(startUrl);
                chargeRecords.setStatus(ChargeRecordsStatusEnum.SEND_SUCCESS.getType());
            } else {
                chargeRecords.setStatus(ChargeRecordsStatusEnum.SEND_FAIL.getType());
            }
            chargeRecordsService.update(chargeRecords);
            System.out.println("start请求结果地址" + startUrl);
            System.out.println("start请求结果" + res);
            return SkJsonResult.ok().setData(((Map<String, Object>) payment.get("expend")).get("pay_info"));
        }

        System.out.println("发起支付回调===》" + JSON.toJSONString(payment));
        System.out.println("=======execute payment end=======");

        return SkJsonResult.fail();


    }


    @PostMapping("/callback")
    public void callback(HttpServletRequest request) {
        try {
//            支付结果
            String type = request.getParameter("type");

            String data = request.getParameter("data");
            String sign = request.getParameter("sign");
            JSONObject backData = JSONObject.parseObject(data);
            //            订单编号
            String orderNo = backData.getString("order_no");

//            支付记录
            ChargeRecordsExt chargeRecords = chargeRecordsService.getDetailByOrderNum(orderNo);
            chargeRecords.setThirdPayId(backData.getString("id"));
            chargeRecords.setThirdOutTransId(backData.getString("out_trans_id"));
            chargeRecords.setThirdPartyOrderId(backData.getString("party_order_id"));

            if ("payment.succeeded".equalsIgnoreCase(type)) {
                chargeRecords.setStatus(ChargeRecordsStatusEnum.PAYED_SUCCESS.getType());
                //验签
                boolean checkSign = AdapaySign.verifySign(data, sign, AdapayCore.PUBLIC_KEY);
                if (!checkSign) {
                    chargeRecords.setStatus(ChargeRecordsStatusEnum.SIGN_FAIL.getType());
                    chargeRecordsService.update(chargeRecords);
                    return;
                }
                String postParamsStr = "out_trade_no=" + orderNo + "&total_fee=" + NumberUtil.multiply(new BigDecimal(backData.getString("pay_amt")), new BigDecimal(100)) + "&playerid=" + chargeRecords.getPayPlayerId() + "&sign=" + urlSign;
                String res = HttpTookit.doGet(okUrl, postParamsStr);
                if (StringUtil.equal(res, "999999")) {
                    chargeRecords.setOkUrl(okUrl);
                    chargeRecords.setStatus(ChargeRecordsStatusEnum.PAY_SEND_SUCCESS.getType());
                } else {
                    chargeRecords.setStatus(ChargeRecordsStatusEnum.PAY_SEND_FAIL.getType());
                }
            }
            if ("payment.failed".equalsIgnoreCase(type)) { //支付失败
                chargeRecords.setStatus(ChargeRecordsStatusEnum.PAY_FAIL.getType());
            }
            System.out.println(YXDate.getFormatDate2String(new Date()) + "  支付结果：" + ChargeRecordsStatusEnum.getChargeRecordsStatusDesc(chargeRecords.getStatus()));
            chargeRecordsService.update(chargeRecords);
        } catch (Exception e) {
            System.out.println(e);
        }
        return;
    }
}
